/**
 * 动态收件人选择器组件
 */
import React, { useState, useEffect } from 'react';
import {
  Modal,
  Steps,
  Button,
  Space,
  Select,
  Form,
  Input,
  Table,
  Card,
  Alert,
  Tag,
  Radio,
  InputNumber,
  Divider,
  Tooltip,
  message,
} from 'antd';
import {
  DatabaseOutlined,
  FilterOutlined,
  UserOutlined,
  EyeOutlined,
  CheckCircleOutlined,
  MailOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {
  getDataSources,
  type DataSourceItem,
} from '@/services/dataSource';
import {
  getDataSourceFields,
  queryDataSourceData,
  type DataSourceField,
  type DataSourceDataPreview,
  FieldType,
} from '@/services/dataSourceField';

const { Option } = Select;
const { Step } = Steps;

interface RecipientSelectorProps {
  visible: boolean;
  onClose: () => void;
  onConfirm: (recipients: RecipientData[]) => void;
  currentDataSourceId?: number;
}

interface RecipientData {
  email: string;
  name?: string;
  variables?: Record<string, any>;
}

interface FilterCondition {
  field: string;
  operator: 'equals' | 'contains' | 'not_equals' | 'greater_than' | 'less_than';
  value: string;
}

const RecipientSelector: React.FC<RecipientSelectorProps> = ({
  visible,
  onClose,
  onConfirm,
  currentDataSourceId,
}) => {
  const [currentStep, setCurrentStep] = useState(0);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  
  // 数据状态
  const [dataSources, setDataSources] = useState<DataSourceItem[]>([]);
  const [selectedDataSource, setSelectedDataSource] = useState<number | undefined>(currentDataSourceId);
  const [fields, setFields] = useState<DataSourceField[]>([]);
  const [emailFields, setEmailFields] = useState<DataSourceField[]>([]);
  const [nameFields, setNameFields] = useState<DataSourceField[]>([]);
  
  // 配置状态
  const [selectedEmailField, setSelectedEmailField] = useState<string>('');
  const [selectedNameField, setSelectedNameField] = useState<string>('');
  const [sendMode, setSendMode] = useState<'batch' | 'personalized'>('batch');
  const [filterConditions, setFilterConditions] = useState<FilterCondition[]>([]);
  const [limit, setLimit] = useState<number>(100);
  
  // 预览状态
  const [previewData, setPreviewData] = useState<DataSourceDataPreview | null>(null);
  const [selectedRecipients, setSelectedRecipients] = useState<RecipientData[]>([]);

  // 获取数据源列表
  const fetchDataSources = async () => {
    try {
      const response = await getDataSources({ page: 1, size: 100 });
      setDataSources(response.items);
      if (!selectedDataSource && response.items.length > 0) {
        setSelectedDataSource(response.items[0].id);
      }
    } catch (error) {
      console.error('获取数据源失败:', error);
    }
  };

  // 获取字段列表
  const fetchFields = async (dataSourceId: number) => {
    setLoading(true);
    try {
      const fieldList = await getDataSourceFields(dataSourceId);
      setFields(fieldList);
      
      // 分类字段
      const emailFieldList = fieldList.filter(f => f.is_email || f.field_type === FieldType.EMAIL);
      const nameFieldList = fieldList.filter(f => f.is_name || f.name.toLowerCase().includes('name'));
      
      setEmailFields(emailFieldList);
      setNameFields(nameFieldList);
      
      // 自动选择第一个邮箱字段
      if (emailFieldList.length > 0) {
        setSelectedEmailField(emailFieldList[0].name);
      }
      
      // 自动选择第一个姓名字段
      if (nameFieldList.length > 0) {
        setSelectedNameField(nameFieldList[0].name);
      }
    } catch (error) {
      console.error('获取字段失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 预览收件人数据
  const previewRecipients = async () => {
    if (!selectedDataSource || !selectedEmailField) {
      message.warning('请先选择数据源和邮箱字段');
      return;
    }

    setLoading(true);
    try {
      // 构建查询条件
      const filters: Record<string, any> = {};
      filterConditions.forEach(condition => {
        if (condition.field && condition.value) {
          filters[condition.field] = condition.value;
        }
      });

      // 查询数据
      const preview = await queryDataSourceData(selectedDataSource, {
        fields: [selectedEmailField, selectedNameField, ...fields.map(f => f.name)].filter(Boolean),
        filters,
        limit,
        offset: 0,
      });

      setPreviewData(preview);

      // 转换为收件人数据
      const recipients: RecipientData[] = preview.data.map(row => ({
        email: row[selectedEmailField] || '',
        name: selectedNameField ? row[selectedNameField] : undefined,
        variables: row,
      })).filter(r => r.email); // 过滤掉没有邮箱的记录

      setSelectedRecipients(recipients);
      message.success(`预览成功，找到 ${recipients.length} 个有效收件人`);
    } catch (error: any) {
      message.error(error.message || '预览失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (visible) {
      fetchDataSources();
    }
  }, [visible]);

  useEffect(() => {
    if (selectedDataSource) {
      fetchFields(selectedDataSource);
    }
  }, [selectedDataSource]);

  // 添加过滤条件
  const addFilterCondition = () => {
    setFilterConditions([...filterConditions, { field: '', operator: 'equals', value: '' }]);
  };

  // 更新过滤条件
  const updateFilterCondition = (index: number, key: keyof FilterCondition, value: string) => {
    const newConditions = [...filterConditions];
    newConditions[index] = { ...newConditions[index], [key]: value };
    setFilterConditions(newConditions);
  };

  // 删除过滤条件
  const removeFilterCondition = (index: number) => {
    setFilterConditions(filterConditions.filter((_, i) => i !== index));
  };

  // 下一步
  const handleNext = () => {
    if (currentStep === 0) {
      if (!selectedDataSource || !selectedEmailField) {
        message.warning('请选择数据源和邮箱字段');
        return;
      }
    } else if (currentStep === 1) {
      previewRecipients();
    }
    setCurrentStep(currentStep + 1);
  };

  // 上一步
  const handlePrev = () => {
    setCurrentStep(currentStep - 1);
  };

  // 确认选择
  const handleConfirm = () => {
    if (selectedRecipients.length === 0) {
      message.warning('没有找到有效的收件人');
      return;
    }
    onConfirm(selectedRecipients);
    onClose();
  };

  // 重置状态
  const handleClose = () => {
    setCurrentStep(0);
    setSelectedRecipients([]);
    setPreviewData(null);
    setFilterConditions([]);
    onClose();
  };

  // 预览表格列定义
  const getPreviewColumns = (): ColumnsType<any> => {
    if (!previewData || previewData.fields.length === 0) return [];
    
    return [
      {
        title: '邮箱地址',
        dataIndex: selectedEmailField,
        key: 'email',
        render: (text: string) => (
          <Space>
            <MailOutlined />
            <span>{text}</span>
          </Space>
        ),
      },
      ...(selectedNameField ? [{
        title: '姓名',
        dataIndex: selectedNameField,
        key: 'name',
        render: (text: string) => text || '-',
      }] : []),
      ...previewData.fields
        .filter(field => field.name !== selectedEmailField && field.name !== selectedNameField)
        .slice(0, 3) // 只显示前3个其他字段
        .map(field => ({
          title: field.display_name || field.name,
          dataIndex: field.name,
          key: field.name,
          ellipsis: true,
          render: (text: any) => {
            if (text === null || text === undefined) return '-';
            if (typeof text === 'object') return JSON.stringify(text);
            return String(text);
          },
        })),
    ];
  };

  const steps = [
    {
      title: '选择数据源',
      content: (
        <div>
          <Form form={form} layout="vertical">
            <Form.Item label="数据源" required>
              <Select
                value={selectedDataSource}
                onChange={setSelectedDataSource}
                placeholder="请选择数据源"
                loading={loading}
              >
                {dataSources.map(ds => (
                  <Option key={ds.id} value={ds.id}>
                    <Space>
                      <DatabaseOutlined />
                      {ds.name} ({ds.type})
                    </Space>
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item label="邮箱字段" required>
              <Select
                value={selectedEmailField}
                onChange={setSelectedEmailField}
                placeholder="请选择邮箱字段"
                loading={loading}
              >
                {emailFields.map(field => (
                  <Option key={field.name} value={field.name}>
                    <Space>
                      <MailOutlined />
                      {field.display_name || field.name}
                      <Tag color="green" size="small">邮箱</Tag>
                    </Space>
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item label="姓名字段">
              <Select
                value={selectedNameField}
                onChange={setSelectedNameField}
                placeholder="请选择姓名字段（可选）"
                allowClear
                loading={loading}
              >
                {nameFields.map(field => (
                  <Option key={field.name} value={field.name}>
                    <Space>
                      <UserOutlined />
                      {field.display_name || field.name}
                      <Tag color="blue" size="small">姓名</Tag>
                    </Space>
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item label="发送模式">
              <Radio.Group value={sendMode} onChange={(e) => setSendMode(e.target.value)}>
                <Radio value="batch">批量发送（所有人收到相同内容）</Radio>
                <Radio value="personalized">个性化发送（每人收到不同内容）</Radio>
              </Radio.Group>
            </Form.Item>
          </Form>
        </div>
      ),
    },
    {
      title: '设置过滤条件',
      content: (
        <div>
          <Alert
            message="过滤条件"
            description="设置过滤条件来筛选收件人，如果不设置则选择所有记录"
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />

          <div style={{ marginBottom: 16 }}>
            <Button type="dashed" onClick={addFilterCondition} block>
              添加过滤条件
            </Button>
          </div>

          {filterConditions.map((condition, index) => (
            <Card key={index} size="small" style={{ marginBottom: 8 }}>
              <Space>
                <Select
                  placeholder="选择字段"
                  value={condition.field}
                  onChange={(value) => updateFilterCondition(index, 'field', value)}
                  style={{ width: 150 }}
                >
                  {fields.map(field => (
                    <Option key={field.name} value={field.name}>
                      {field.display_name || field.name}
                    </Option>
                  ))}
                </Select>

                <Select
                  value={condition.operator}
                  onChange={(value) => updateFilterCondition(index, 'operator', value)}
                  style={{ width: 120 }}
                >
                  <Option value="equals">等于</Option>
                  <Option value="contains">包含</Option>
                  <Option value="not_equals">不等于</Option>
                  <Option value="greater_than">大于</Option>
                  <Option value="less_than">小于</Option>
                </Select>

                <Input
                  placeholder="输入值"
                  value={condition.value}
                  onChange={(e) => updateFilterCondition(index, 'value', e.target.value)}
                  style={{ width: 150 }}
                />

                <Button
                  type="text"
                  danger
                  onClick={() => removeFilterCondition(index)}
                >
                  删除
                </Button>
              </Space>
            </Card>
          ))}

          <Divider />

          <Form.Item label="限制数量">
            <InputNumber
              value={limit}
              onChange={(value) => setLimit(value || 100)}
              min={1}
              max={10000}
              style={{ width: 150 }}
            />
            <span style={{ marginLeft: 8, color: '#666' }}>
              最多选择的收件人数量
            </span>
          </Form.Item>
        </div>
      ),
    },
    {
      title: '预览收件人',
      content: (
        <div>
          {previewData ? (
            <div>
              <Alert
                message={`找到 ${selectedRecipients.length} 个有效收件人`}
                description={`发送模式：${sendMode === 'batch' ? '批量发送' : '个性化发送'}`}
                type="success"
                showIcon
                style={{ marginBottom: 16 }}
              />

              <Table
                columns={getPreviewColumns()}
                dataSource={previewData.data}
                rowKey={(record, index) => index?.toString() || '0'}
                pagination={false}
                scroll={{ x: 'max-content' }}
                size="small"
              />
            </div>
          ) : (
            <div style={{ textAlign: 'center', padding: 50, color: '#999' }}>
              请点击"预览收件人"按钮查看数据
            </div>
          )}
        </div>
      ),
    },
  ];

  return (
    <Modal
      title="选择收件人"
      open={visible}
      onCancel={handleClose}
      width={900}
      footer={null}
      style={{ top: 20 }}
    >
      <Steps current={currentStep} style={{ marginBottom: 24 }}>
        {steps.map(step => (
          <Step key={step.title} title={step.title} />
        ))}
      </Steps>

      <div style={{ minHeight: 400 }}>
        {steps[currentStep].content}
      </div>

      <div style={{ marginTop: 24, textAlign: 'right' }}>
        <Space>
          {currentStep > 0 && (
            <Button onClick={handlePrev}>
              上一步
            </Button>
          )}
          {currentStep < steps.length - 1 && (
            <Button type="primary" onClick={handleNext} loading={loading}>
              {currentStep === 1 ? '预览收件人' : '下一步'}
            </Button>
          )}
          {currentStep === steps.length - 1 && (
            <Button
              type="primary"
              icon={<CheckCircleOutlined />}
              onClick={handleConfirm}
              disabled={selectedRecipients.length === 0}
            >
              确认选择 ({selectedRecipients.length} 人)
            </Button>
          )}
        </Space>
      </div>
    </Modal>
  );
};

export default RecipientSelector;
